import { onBeforeUnmount, onMounted } from 'vue'

const scale = {
  width: '1',
  height: '1',
}

// * 设计稿尺寸（px）
const baseWidth = 1920
const baseHeight = 1080

// * 需保持的比例（默认1.77778）
const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5))

//初始化useDraw函数时需要传入组件实例(响应式)
export function useDraw(appRef) {
  let drawTiming = null
  const calcRate = () => {
    if (!appRef.value) return
    // 当前宽高比
    const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5))
    if (appRef.value) {
      if (currentRate > baseProportion) {
        // 表示更宽
        scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5)
        scale.height = (window.innerHeight / baseHeight).toFixed(5)
        appRef.value.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
      } else {
        // 表示更高
        scale.height = (window.innerWidth / baseProportion / baseHeight).toFixed(5)
        scale.width = (window.innerWidth / baseWidth).toFixed(5)
        appRef.value.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
      }
    }
  }
  const resize = () => {
    clearTimeout(drawTiming)
    drawTiming = setTimeout(() => {
      calcRate(appRef)
    }, 200)
  }
  onMounted(() => {
    calcRate()
    window.addEventListener('resize', resize, false)
  })
  onBeforeUnmount(() => {
    window.removeEventListener('resize', resize, false)
  })
  return {
    calcRate,
    resize,
  }
}
